<template>
  <div id="xmind">
    <el-row>
      <el-col
        :span="4"
        v-for="(o, index) in projects"
        :key="o.id"
        :offset="index > 0 ? 2 : 0"
      >
        <el-card :body-style="{ padding: '0px' }">
          <img src="img/photo.jpg" height="200px" @click="openDialog(o.id)" />
          <div style="padding: 14px">
            <span>{{ o.projectName }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="outerVisible" width="98%" top="3vh">
      <!-- <template slot="title"> 标题 </template> -->

      <!-- <div class="xmind-menu"> -->
      <!-- <el-row :gutter="20"> -->
      <!-- <el-col :span="4"> -->
      <!-- <div class="grid-content bg-purple"> -->
      <!-- <el-button type="info" plain @click="addFile">添加文件</el-button> -->
      <!-- <el-button type="info" plain @click="hiddenAside">放大</el-button> -->
      <!-- <el-button type="info" plain>添加文件</el-button> -->
      <!-- </div> -->
      <!-- </el-col> -->
      <!-- <el-col :span="16"> -->
      <!-- <div class="grid-content bg-purple"> -->
      <!-- <el-button type="info" plain @click="addFile">编辑</el-button> -->
      <!-- <el-button type="info" plain @click="saveData" :icon="loading"
                >保存</el-button
              > -->
      <!-- </div></el-col
          > -->
      <!-- <el-col :span="4" -->
      <!-- ><div class="grid-content bg-purple"> -->
      <!-- <el-button type="info" plain @click="copyTestcase">复制</el-button>
              <el-button type="info" plain @click="pasteTestcase">粘贴</el-button> -->
      <!-- <el-tooltip placement="top"> -->
      <!-- <div slot="content"> -->
      <!-- ↑↓←→:节点选择移动<br> -->
      <!-- tab:增加子节点<br> -->
      <!-- enter:增加兄弟节点<br> -->
      <!-- del:删除节点<br> -->
      <!-- ctrl+c:复制节点<br> -->
      <!-- ctrl+v:粘贴节点<br> -->
      <!-- </div> -->
      <!-- <el-button>Top center</el-button> -->
      <!-- </el-tooltip> -->
      <!-- </div></el-col -->
      <!-- >
        </el-row> -->
      <!-- </div> -->
      <!-- <el-divider></el-divider>s -->
      <div
        class="xmind"
        @keydown.ctrl.67="nodeCopy"
        @keydown.ctrl.86="nodePaste"
      >
        <div class="xmind-aside">
          <div class="xmind-aside-top">
            <h3>销售管理系统</h3>
            <div>
              <el-button type="text" @click="addFile"
                ><i class="el-icon-circle-plus-outline icon-size"></i
              ></el-button>
            </div>
          </div>
          <filetag
            @select="selectFile"
            v-for="item in fileArray"
            :fileName="item.fileName"
            :id="item.id"
            :key="item.id"
            :class="{ active: isActive === item.id }"
            @delete="deleteFile"
          ></filetag>
        </div>
        <div class="xmind-main">
          <div class="xmind-main-nav">
            <input class="title" />
            <div class="btn-group">
              <el-tooltip placement="top">
                -->
                <span slot="content">
                  ↑↓←→:节点选择移动<br />
                  tab:增加子节点<br />
                  enter:增加兄弟节点<br />
                  del:删除节点<br />
                  ctrl+c:复制节点<br />
                  ctrl+v:粘贴节点<br />
                </span>
                <el-button type="text">说明</el-button>
              </el-tooltip>

              <el-button type="text" @click="downloadXmindFile"
                ><i class="el-icon-download icon-size-18"></i
              ></el-button>

              <el-button type="text" @click="saveData"
                ><i class="el-icon-refresh icon-size-18"></i
              ></el-button>
              <el-button type="text"
                ><i class="el-icon-full-screen icon-size-18"></i
              ></el-button>
            </div>
          </div>

          <div class="xmind-container">
            <div id="xmind-container" @click="getXmindNode"></div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>




<script>
import FileTag from "./components/FileTag.vue";
import { v4 as uuidv4 } from "uuid";
import "jsmind/style/jsmind.css";
import jsMind from "jsmind/js/jsmind.js";
import { addFile, queryFile } from "@/api/file";
import {
  saveTestcase,
  getTestcase,
  exportXmindFile,
  deleteTestcase,
} from "@/api/testcase";
import { getProjects } from "@/api/project";

// import { forEach } from 'mock/user';
window.jsMind = jsMind;
const options = {
  container: "xmind-container", // [必选] 容器的ID
  editable: true, // 是否启用编辑
  theme: "success", // 主题
  mode: "side", // 布局模式
  support_html: true, // 是否支持节点里的HTML元素
  log_level: "info", // 日志级别
  view: {
    engine: "canvas", // 思维导图各节点之间线条的绘制引擎
    hmargin: 100, // 思维导图距容器外框的最小水平距离
    vmargin: 50, // 思维导图距容器外框的最小垂直距离
    line_width: 2, // 思维导图线条的粗细
    line_color: "#555", // 思维导图线条的颜色
    draggable: true, // 当容器不能完全容纳思维导图时，是否允许拖动画布代替鼠标滚动
    hide_scrollbars_when_draggable: false, // 当设置 draggable = true 时，是否隐藏滚动条
  },
  layout: {
    hspace: 30, // 节点之间的水平间距
    vspace: 20, // 节点之间的垂直间距
    pspace: 13, // 节点与连接线之间的水平间距（用于容纳节点收缩/展开控制器）
  },
  shortcut: {
    enable: true, // 是否启用快捷键
    handles: {}, // 命名的快捷键事件处理器
    mapping: {
      // 快捷键映射
      // addchild: [45, 4096 + 13], // <Insert>, <Ctrl> + <Enter>
      addbrother: 13, // <Enter>
      editnode: 32, // <F2>
      delnode: 46, // <Delete>
      // toggle: 32, // <Space>
      left: 37, // <Left>
      up: 38, // <Up>
      right: 39, // <Right>
      down: 40, // <Down>
    },
  },
};

export default {
  data() {
    return {
      isActive: "",
      projects: [],
      currentProjectId: null,
      outerVisible: false,
      dialogFormVisible: false,
      xmindboardHeight: "",
      asideBarHidden: true,
      fileArray: [],
      xmindContainerStyle: "",
      jm: null,
      // idArray: new Set(),
      // currentTable: [{ step: "", result: "" }],
      // testcaseMap: new Map(),
      fileId: "",
      loading: "",
      copyTs: [],
      paste: [],
      nodeCope: null,
    };
  },
  watch: {},

  components: {
    filetag: FileTag,
  },
  methods: {
    openDialog: function (value) {
      queryFile(value).then((res) => {
        this.currentProjectId = value;
        this.fileArray = res.data;

        this.outerVisible = true;
      });
    },

    hiddenAside: function () {
      this.asideBarHidden = !this.asideBarHidden;
      if (this.xmindContainerStyle !== "margin-left:200px") {
        this.xmindContainerStyle = "margin-left:0px";
      } else {
        this.xmindContainerStyle = "margin-left:200px";
      }
    },

    addXmindChild: function () {
      if (document.activeElement.className !== "jsmind-inner") {
        return;
      }
      if (!this.jm.get_selected_node()) {
        return;
      }
      let node = this.jm.get_selected_node();
      // console.log(node)
      let uuid = uuidv4();
      this.jm.add_node(node, uuid, "Easy");
      let nextNode = this.jm.get_node(uuid);
      this.jm.select_node(nextNode);
      this.jm.begin_edit(nextNode);
    },

    addXmindBrother: function () {
      // console.log("添加兄弟节点")
      if (!this.jm.get_selected_node()) {
        return;
      }
    },

    deleteXmindChild: function () {
      // console.log("删除节点")
      if (!this.jm.get_selected_node()) {
        return;
      }
    },

    getXmindNode: function () {
      if (!this.jm.get_selected_node()) {
        return;
      }
      let node = this.jm.get_selected_node();
      let id = node.id;
      // this.currentTable = this.testcaseMap.get(id)
    },

    addFile() {
      this.$prompt("请输入文件名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          addFile({ fileName: value, projectId: this.currentProjectId }).then(
            (res) => {
              this.fileArray.push(res.data);
              this.fileId = res.data.id;
              // this.currentTable =[]
              this.openXmind();
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },

    openXmind: function () {
      var mind = {
        /* 元数据，定义思维导图的名称、作者、版本等信息 */
        meta: {
          name: "jsMind-demo-tree",
          author: "hizzgdev@163.com",
          version: "0.2",
        },
        /* 数据格式声明 */
        format: "node_tree",
        /* 数据内容 */
        data: { id: "root", topic: "jsMind", children: [] },
      };

      if (this.jm === null) {
        this.jm = new jsMind(options);
      }

      this.jm.show(mind);
    },

    selectFile(value) {
      const { id, fileName } = value;
      this.fileId = id;
      this.isActive = id;
      getTestcase(id).then((res) => {
        const { xmind, testcases } = res.data;
        if (xmind == undefined || xmind == null) {
          this.jm.show();
          return;
        } else {
          if (this.jm == null) {
            this.jm = new jsMind(options);
          }

          this.jm.show(JSON.parse(xmind.mind));
        }
      });
    },
    saveData() {
      // this.loading = "el-icon-loading";
      let postdata = {
        xmind: {
          fileId: this.fileId,
        },
        testcases: [],
      };
      let titleMap = new Map();
      let data = this.jm.get_data("node_tree");

      postdata.xmind["mind"] = JSON.stringify(data);

      saveTestcase(postdata).then((res) => {
        this.loading = "";
        this.$message({
          message: res.msg,
          type: "success",
        });
      });
    },

    refreshTestcaseMap(list) {
      for (let key of list) {
        if (!this.testcaseMap.has(key)) {
          let tableData = [
            { step: "", result: "" },
            { step: "", result: "" },
            { step: "", result: "" },
            { step: "", result: "" },
            { step: "", result: "" },
          ];
          this.testcaseMap.set(key, tableData);
        }
      }
      for (let id of this.testcaseMap.keys()) {
        if (!list.has(id)) {
          this.testcaseMap.delete(id);
        }
      }
    },

    tree2titleMap(data, map, title) {
      if (!data.children) {
        // title = title+'-'+data.topic
        map.set(data.id, title);
      } else {
        for (let child of data.children) {
          let title1 = title + "-" + child.topic;
          this.tree2titleMap(child, map, title1);
        }
      }
    },

    tree2List(data, list) {
      // console.log(data)
      if (!data.children) {
        list.add(data.id);
      } else {
        for (let child of data.children) {
          this.tree2List(child, list);
        }
      }
    },
    copyTestcase() {
      let node = this.jm.get_selected_node();
      if (node.children.length !== 0) return;
      this.copyTs = [];
      for (let data of this.currentTable) {
        const { step, result } = data;
        this.copyTs.push({
          step,
          result,
        });
      }
      // if(node.ch)
    },

    pasteTestcase() {
      let node = this.jm.get_selected_node();
      if (node.children.length !== 0) return;
      this.currentTable.splice(0, this.currentTable.length);
      for (let data of this.copyTs) {
        this.currentTable.push(data);
      }
    },

    addRow() {
      if (!this.currentTable) {
        return;
      }
      this.currentTable.push({
        step: "",
        result: "",
      });
    },

    nodeCopy() {
      this.nodeCope = this.jm.get_selected_node();
    },

    nodePaste() {
      let node = this.jm.get_selected_node();
      if (node !== null && this.nodeCope !== null) {
        this.pasteNodeDeep(node, this.nodeCope);
      }
    },

    pasteNodeDeep(insertNode, copyNode) {
      const topic = copyNode.topic;
      const children = copyNode.children;
      let uuid = uuidv4();
      this.jm.add_node(insertNode, uuid, topic);
      let nextNode = this.jm.get_node(uuid);
      if (children.length === 0) {
        return;
      } else {
        for (let i = 0; i < children.length; i++) {
          this.pasteNodeDeep(nextNode, children[i]);
        }
      }
    },

    downloadXmindFile() {
      exportXmindFile(this.fileId, "测试用例.zip");
    },

    deleteFile(file) {
      // console.log(id)
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteTestcase(file.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });

            queryFile(this.currentProjectId).then((res) => {
              this.currentProjectId = value;
              this.fileArray = res.data;
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  mounted: function () {
    // var jm = new jsMind(options);
    // jm.show();
    let _this = this;
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      if (key == 9) {
        _this.addXmindChild();
      } else if (key == 13) {
        _this.addXmindBrother();
      } else if (key == 46) {
        _this.deleteXmindChild();
      }
    };

    getProjects().then((res) => (this.projects = res.data));
  },
  beforeMount() {
    document.onkeydown = null;
  },
};
</script>

<style>
.title {
  background-color: #4a5056;
  color: white;
  padding-left: 1em;
}

.btn-group {
  float: right;
}
.icon-size {
  font-size: 30px;
}

.icon-size-18 {
  font-size: 18px;
}

.xmind {
  position: relative;
  height: 95vh;
}

#xmind {
  padding-left: 15px;
  padding-top: 15px;
}

#xmind .el-dialog__body {
  padding: 0px;
}

#xmind .el-dialog__header {
  height: 0px;
  padding: 0px;
}

/* #xmind .xmind-menu {
  width: 100%;
  height: 35px;
  margin-bottom: 5px;
  /* position: fixed; */
/* background: black; */
/* top:0px */
/* } */

.xmind .xmind-aside {
  width: 200px;
  /* position: absolute; */
  /* background: black; */
  /* border: 1px solid gray; */
  /* top: 0px;
  left: 0px; */

  height: 95vh;
  float: left;
  background: #fafbfc;
  background-color: rgb(250, 251, 252);
  background-position-x: 0%;
  background-position-y: 0%;
  background-repeat: repeat;
  background-attachment: scroll;
  background-image: none;
  background-size: auto;
  background-origin: padding-box;
  background-clip: border-box;
}

.xmind-aside .xmind-aside-top {
  height: 100px;
  width: 200px;
  background-color: #393d41;
  color: white;
  text-align: center;
  padding-top: 15px;
}

.xmind .xmind-main {
  height: 95vh;
  margin-left: 200px;
  /* margin-top: 50px; */
}

.xmind .xmind-main .xmind-main-nav {
  height: 40px;
  /* float: top right; */
  background-color: #4a5056;
  line-height: 40px;
}
hr {
  margin: 0px;
}
.xmind .xmind-container {
  /* background: red; */
  /* height: calc(95vh-50px); */
  /* margin-left: 200px; */
  /* margin-right: 300px; */
  height: calc(100% - 42px);
}
.xmind #xmind-container {
  /* background: red; */
  /* height: calc(95vh-50px); */
  /* margin-left: 200px; */
  /* margin-right: 300px; */
  height: 100%;
}

.active {
  background-color: #393d41;
}
</style>
